package cn.jhc.dao;

import cn.jhc.entity.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

public interface UserDAO {
    @Insert("insert into t_user(username,password,email,root) values(#{username},#{password},#{email},#{root})")
    @SelectKey(statement = "select last_insert_id()",keyProperty = "userId",before = false,resultType = Integer.class)
    public int save(User user);

    @Update({"<script>",
            "update t_user",
            "  <set>",
            "    <if test='username != null'>username=#{username},</if>",
            "    <if test='password != null'>password=#{password},</if>",
            "    <if test='email != null'>email=#{email},</if>",
            "    <if test='root != null'>root=#{root},</if>",
            "  </set>",
            "where user_id=#{userId}",
            "</script>"})
    public int update(User user);

    @Delete("delete from t_user where user_id=#{user_id}")
    public int delete(Integer userId);

    @Select("select * from t_user where user_id=#{userId}")
    public User queryOne(Integer userId);

    @Select({"<script>",
            "select * from t_user",
            "  <where>",
            "    <if test='username != null'>username like '%${username}%'</if>",
            "    <if test='password != null'>password=#{password}</if>",
            "    <if test='email != null'>email=#{email}</if>",
            "    <if test='root != null'>root like '%${root}%'</if>",
            "  </where>",
            "</script>"})
    public List<User> query(User user);


    @Select("select * from t_user where user_id=#{userId}")
    @Results(id="userMap",value = {
            @Result(property = "userId",column = "user_id"),
            @Result(property = "password",column = "password"),
            @Result(property = "email",column = "email"),
            @Result(property = "root",column = "root"),
            @Result(property = "orders",column = "user_id",
                    many = @Many(select = "cn.jhc.dao.OrderDAO.QueryByUser",fetchType = FetchType.LAZY))


    })
    public User findUserOrders(Integer userId);
}
